import { constantRoutes } from "@/router";
import { getRouters } from "@/api/menu";
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";
import InnerLink from "@/layout/components/InnerLink";
import user from "./user";
import app_module from "./app";
import i18n from "../../lang";

const permission = {
  state: {
    routes: [],
    appRoutes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes);
    },
    SET_APP_ROUTES: (state, routes) => {
      state.appRoutes = routes;
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      // 顶部导航菜单默认添加统计报表栏指向首页
      state.topbarRouters = routes;
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes;
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }, langObj) {
      const lang = langObj || app_module.state;
      return new Promise((resolve) => {
        // 向后端请求路由数据
        getRouters(lang).then((res) => {
          const appName = process.env.VUE_APP_NAME;
          let sidebarRoutes = [];
          const iqc = res.data.find((o) => o.path == appName);
          if (iqc) {
            const data = iqc.children;
            const pageRoutes = data.map((i) => {
              i.path = `/${i.path}`;
              i.component = "Layout";
              return i;
            });
            sidebarRoutes = filterAsyncRouter(pageRoutes, false, false);
            //初始菜单到国际化配置项中
            initI18nMessages(pageRoutes, lang);
            console.log("i18nByLang", i18nByLang);
            commit("SET_SIDEBAR_ROUTERS", sidebarRoutes);
            commit("SET_DEFAULT_ROUTES", sidebarRoutes);
            commit("SET_APP_ROUTES", [data]);
            commit("SET_TOPBAR_ROUTES", sidebarRoutes);
          }
          resolve(iqc ? sidebarRoutes : []);
        });
      });
    },
  },
};
let i18nByLang = {};
function initI18nMessages(topbarRoutes, langObj) {
  topbarRoutes.map((menu) => {
    // if (menu.hidden) {
    //   return null
    // }
    return renderItem(menu);
  });
  let language_obj = i18n.messages[langObj.language];
  let message = {
    ...language_obj,
    routes: { ...language_obj.routes, ...i18nByLang },
  };
  i18n.setLocaleMessage(langObj.language, message);
}
function renderItem(menu) {
  // if (!menu.hidden) {
  return menu.children ? renderSubMenu(menu) : renderMenuItem(menu);
  // }
  // return null
}
function renderMenuItem(menu) {
  if (menu.meta) {
    i18nByLang[`${menu.path}`] = menu.meta.title;
  }
}
function renderSubMenu(menu) {
  if (menu.path) {
    renderMenuItem(menu);
    const pre = menu.path == "/" ? menu.path : `${menu.path}/`;
    menu.children.forEach((item) => {
      renderItem({ ...item, path: `${pre}${item.path}` });
    });
  }
}
// 遍历路由二级对象
function filterTopRouter(sidebarRoutes) {
  let topRouters = [];
  const appid = user.state.appId;
  let topArray = sidebarRoutes.filter((route) => {
    return route.meta.id == appid;
  });
  if (
    topArray &&
    topArray.length == 1 &&
    topArray[0].children &&
    topArray[0].children.length > 0
  ) {
    topRouters = topArray[0].children;
  }
  return topRouters;
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  // debugger
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      if (route.name === "抽样方案") {
        console.log("抽样方案========", route.component);
      }
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else if (route.component === "ParentView") {
        route.component = ParentView;
      } else if (route.component === "InnerLink") {
        route.component = InnerLink;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === "ParentView" && !lastRouter) {
        el.children.forEach((c) => {
          c.path = el.path + "/" + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path;
    }
    children = children.concat(el);
  });
  return children;
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === "development") {
    return (resolve) =>
      require([`@/views/${view}`], resolve, function () {
        throw `加载${view}页面错误`;
      });
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`);
  }
};


export default permission;
